package com.example.luke.shengdangxiaoattendance.Common;

import android.app.ActionBar;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Color;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.nfc.NfcAdapter;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;


import com.example.luke.shengdangxiaoattendance.MainActivity;
import com.example.luke.shengdangxiaoattendance.R;
import com.example.luke.shengdangxiaoattendance.Util.GlobalFunction;
import com.example.luke.shengdangxiaoattendance.Util.MIReader;
import com.example.luke.shengdangxiaoattendance.Util.ZYScanner;
import com.wilddog.client.SyncReference;
import com.wilddog.client.WilddogSync;
import com.wilddog.wilddogcore.WilddogApp;
import com.wilddog.wilddogcore.WilddogOptions;

import java.util.Locale;

//import com.example.yrdev.ordering_system.R;
//import com.example.yrdev.ordering_system.Utils.GlobalFunction;
//import com.example.yrdev.ordering_system.Utils.MIReader;

/**
 * Created by yrdev on 7/18/16.
 */

public class CommonActivity extends AppCompatActivity {
     public Context context;

   public    MIReader reader;
    public NfcAdapter mNfcAdapter;
    private PendingIntent mPendingIntent;
    private IntentFilter tagDetected = null;
    public String pwdData;
  public   ZYScanner zyScanner;
    public SyncReference ref;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        ButterKnife.inject(this);

         //   showCustomActionBar();
            //initView();
        context=this;


        //Thread.setDefaultUncaughtExceptionHandler();
    }

    public void initView(){


    }



    String wildDogUrl="https://wd1156633058urimvl.wilddogio.com";
    public  void initWildDog(){

        WilddogOptions options=new WilddogOptions.Builder().setSyncUrl(wildDogUrl).build();
        WilddogApp.initializeApp(this,options);
        ref   = WilddogSync.getInstance().getReference();


    }


    private static final String ACTION_USB_PERMISSION =
            "com.android.example.USB_PERMISSION";

  public  void requestUsbPermission(){
     final    UsbManager mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);

      final   PendingIntent mPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);
        IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);


        BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {

            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
                if (ACTION_USB_PERMISSION.equals(action)) {
                    synchronized (this) {
                        UsbDevice device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);

                        if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
                            if(device != null){
                                //call method to set up device communication
                                mUsbManager.requestPermission(device, mPermissionIntent);

                            }
                        }
                        else {

                        }
                    }
                }
            }
        };


        registerReceiver(mUsbReceiver, filter);

    }

    public void restartApplication() {
        Intent intent = new Intent(getApplicationContext(),MainActivity.class);
        PendingIntent restartIntent = PendingIntent.getActivity(
                this, 0, intent,
                PendingIntent.FLAG_CANCEL_CURRENT);
        //退出程序
        AlarmManager mgr = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
        mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100,
                restartIntent); // 1秒钟后重启应用
       //finishActivity();
        System.exit(0); //结束进程之前可以把你程序的注销或者退出代码放在这段代码之前
    }

    public   void initLanguage(String key){

        Locale myLocale= new Locale(key);
        Resources res=getResources();
        DisplayMetrics dm=res.getDisplayMetrics();
        Configuration configuration=res.getConfiguration();
        configuration.locale=myLocale;
        res.updateConfiguration(configuration,dm);


    }


    public  void restart(){
        Intent intent = getIntent();
        finish();
        startActivity(intent);
    }

    public void initNFCParam(){

        zyScanner=new ZYScanner(this);
        GlobalFunction.context=this;

//        reader=new MIReader(this);
//        // reader.setREAD_SECTOR(Setting.getInstance().getWritingSector());
//
//        mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
//        init_NFC();
//        mPendingIntent =
//                PendingIntent.getActivity(this, 0, new Intent(this,
//                        getClass()), 0);

//      String temp=MIReader.bytesToHexString(dhF9Jni.calculatePass());
//
//
//        pwdData=temp;


    }
    private void init_NFC() {
        // 初始化PendingIntent，当有NFC设备连接上的时候，就交给当前Activity处理

        // 新建IntentFilter，使用的是第二种的过滤机制
        tagDetected = new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED);
        tagDetected.addCategory(Intent.CATEGORY_DEFAULT);
    }


    @Override
    protected void onResume() {
        super.onResume();

        if (mNfcAdapter != null) {
            mNfcAdapter.enableForegroundDispatch(this, mPendingIntent, null, null);
        //   GlobalFunction.ToastAlert(this,"start processing");

//            if (NfcAdapter.ACTION_TECH_DISCOVERED.equals(this.getIntent()
//                    .getAction())) {
//                // 注意这个if中的代码几乎不会进来，因为刚刚在上一行代码开启了监听NFC连接，下一行代码马上就收到了NFC连接的intent，这种几率很小
//                // 处理该intent
//                processIntent(this.getIntent());
//
//                //Toast.makeText(this, "get action after startNFC_Listener", Toast.LENGTH_LONG).show();
//            }
        }

    }


    public void  showCustomActionBar(){
     getSupportActionBar().setDisplayOptions( ActionBar.DISPLAY_SHOW_CUSTOM);
     //   getSupportActionBar().setCustomView(R.layout.action_bar);

//        ActionBar bar = getActionBar();
//        bar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#0000ff")));


    }
    public void setBarTitle(String str){
//        TextView textView=(TextView)getSupportActionBar().getCustomView().findViewById(R.id.actionBar_title);
//        textView.setText(str);
    }
    public void showBackButton(){

        ImageButton backButton=new ImageButton(this);

        RelativeLayout.LayoutParams layoutParams=new RelativeLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        layoutParams.addRule(RelativeLayout.CENTER_VERTICAL);
     //   backButton.setImageResource(R.drawable.back_button);
        backButton.setBackgroundColor(Color.TRANSPARENT);

        backButton.setLayoutParams(layoutParams);

    //   RelativeLayout layout=(RelativeLayout)getSupportActionBar().getCustomView().findViewById(R.id.action_bar_layout);

//        layout.addView(backButton);
//
//        backButton.setOnClickListener(new View.OnClickListener() {
//         @Override
//         public void onClick(View view) {
//
//             finish();
//             overridePendingTransition(R.anim.trans_right_in, R.anim.trans_right_out);
//         }
//
//       });

        getSupportActionBar().setHomeButtonEnabled(true);
    }
    public void showRightButtonWithListener(View.OnClickListener onClickListener, String title){
        Button backButton=new Button(this);
        RelativeLayout.LayoutParams layoutParams=new RelativeLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
      //  layoutParams.addRule(RelativeLayout.CENTER_VERTICAL);
        layoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
        layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);

        backButton.setText(title);
        backButton.setTextColor(Color.parseColor("#ffffff"));
        backButton.setLayoutParams(layoutParams);
        backButton.setBackgroundColor(Color.TRANSPARENT);
        backButton.setTextSize(19);
        backButton.setGravity(Gravity.RIGHT);

//        RelativeLayout layout=(RelativeLayout)getSupportActionBar().getCustomView().findViewById(R.id.action_bar_layout);
//
//        layout.addView(backButton);

        backButton.setOnClickListener(onClickListener);


        getSupportActionBar().setHomeButtonEnabled(true);
    }

  public void hideKeyBoard(){
      View view = this.getCurrentFocus();
      if (view != null) {

          InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
          imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
      }
  }
    public void activatePushingAnim(){
        //overridePendingTransition(R.anim.trans_left_in, R.anim.trans_left_out);
    }

    public void gotoActivityWithObject(Class activityClass, int requestCode, String key, String value){
        Intent intent=new Intent();
        intent.setClass(getApplicationContext(),activityClass);
        intent.putExtra(key,value);

        startActivityForResult(intent, requestCode); 
    }


 public    void gotoActivity(Class activityClass, int requestCode){
        Intent intent=new Intent();
        intent.setClass(getApplicationContext(), activityClass);
        startActivityForResult(intent,requestCode);
    }
    public  void gotoActivity(Class activityClass){

      gotoActivity(activityClass,0);

    }


    public  void gotoActivityWithIntent(Intent intent, Class activityClass, int requestCode){

        intent.setClass(getApplicationContext(),activityClass);
        startActivityForResult(intent,requestCode);
    }

//    @Override
//    protected void onDestroy() {
//        restartApplication();
//        super.onDestroy();
//
//    }
}
